﻿import dayjs from 'dayjs'
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {string} date YYYY-MM-DD | YYYY-MM-DD HH:mm:ss
 * @returns {string}
 */
export function formatTime(date) {
  const mistiming = Math.round((Date.now() - new Date(date).getTime()) / 1000)
  const tags = ['年', '个月', '星期', '天', '小时', '分钟', '秒']
  const times = [31536000, 2592000, 604800, 86400, 3600, 60, 1]
  for (let i = 0; i < times.length; i++) {
    const inm = Math.floor(mistiming / times[i])
    if (tags[i] === '天') {
      switch (inm) {
        case 0:
          return '今天'
        case 1:
          return '昨天'
        case 2:
          return '前天'
        default:
          return inm + tags[i] + '前'
      }
    }
    if (inm !== 0) {
      return inm + tags[i] + '前'
    }
  }
}

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
const DATE_FORMAT = 'YYYY-MM-DD'

export function formatToDateTime(date: dayjs.Dayjs | undefined = undefined, format = DATE_TIME_FORMAT): string {
  return dayjs(date).format(format)
}

export function formatToDate(date: dayjs.Dayjs | undefined = undefined, format = DATE_FORMAT): string {
  return dayjs(date).format(format)
}

export const dateUtil = dayjs

export const getTimeState = () => {
  // 获取当前时间
  const timeNow = new Date()
  // 获取当前小时
  const hours = timeNow.getHours()
  // 设置默认文字
  let state = ``
  // 判断当前时间段
  if (hours >= 0 && hours <= 10) {
    state = `早上好`
  } else if (hours > 10 && hours <= 14) {
    state = `中午好`
  } else if (hours > 14 && hours <= 18) {
    state = `下午好`
  } else if (hours > 18 && hours <= 24) {
    state = `晚上好`
  }
  return state
}
